package com.beiding.natgo.server;

import com.beiding.natgo.common.Message;
import lombok.extern.slf4j.Slf4j;

import javax.websocket.Session;
import java.io.IOException;
import java.io.ObjectOutputStream;
import java.util.Timer;
import java.util.TimerTask;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

@Slf4j
public class SessionHolder {

    //连接
    private Session session;

    //服务端工作器
    private ServerWorker serverWorker;

    //上次心跳时间
    private long lastHeartBeat = System.currentTimeMillis();

    private Integer port;


    public SessionHolder(Session session) {
        this.session = session;
    }

    //关闭
    public void close() {
        try {
            session.close();
            if (this.serverWorker != null) {
                this.serverWorker.stop();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    //向通道写入消息
    public void writeData(String chanelId, byte[] data) {
        serverWorker.writeData(chanelId, data);
    }


    //初始化端口
    public void initPort(Integer port) {
        this.port = port;
        serverWorker = new ServerWorker(this, port);
        serverWorker.start();
    }

    private ExecutorService executorService = Executors.newFixedThreadPool(1);

    //向客户端发送消息
    public void send(Message message) {
        executorService.submit(() -> {
            try {
                ObjectOutputStream outputStream = new ObjectOutputStream(session.getBasicRemote().getSendStream());
                outputStream.writeObject(message);
                outputStream.close();
             //   log.info("消息已送达 type={}  msg={}", message.getType(), message.getMsg());
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
        });
    }

    //发送初始化成功
    public void sendInitSuccess() {
        Message message = new Message();
        message.setType(9);
        send(message);
    }

    //发送初始化失败
    public void sendInitFail(String msg) {
        Message message = new Message();
        message.setMsg(msg);
        message.setType(3);
        send(message);
    }

    //向客户端发送数据
    public void sendData(String chanelId, byte[] data) {
        Message message = new Message();
        message.setType(1);
        message.setChanelId(chanelId);
        message.byteData(data);
        send(message);
    }

    //向客户端发送创建新连接
    public void sendCreateConnect(String chanelId) {
        Message message = new Message();
        message.setChanelId(chanelId);
        message.setType(4);
        send(message);
    }

    //发送服务端处理异常
    public void sendServerError(String msg) {
        Message message = new Message();
        message.setType(6);
        message.setMsg(msg);
        send(message);
    }

    //向客户端发送关闭通道
    public void sendCloseChanel(String id) {
        Message message = new Message();
        message.setChanelId(id);
        message.setType(7);
        send(message);
    }

    //关闭通道
    public void closeChanel(String chanelId) {
        log.info("收到关闭连接请求{}",chanelId);
        this.serverWorker.closeChanel(chanelId);
    }

    public void createChanelSuccess(String cid) {
        this.serverWorker.createChanelSuccess(cid);
    }

    public void createChanelFail(String cid) {
        this.serverWorker.createChanelFail(cid);
    }

    public void heartBeat() {
        lastHeartBeat = System.currentTimeMillis();
    }

    public long getLastHeartBeat() {
        return lastHeartBeat;
    }

    public Integer getPort() {
        return port;
    }

    public Session getSession() {
        return session;
    }
}
